package com.mes.cloud.util;

import com.google.common.collect.Maps;
import com.googlecode.aviator.AviatorEvaluator;
import com.mes.cloud.enums.ValidatorMsgEnums;

import java.text.MessageFormat;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VadatorParam {
    private static final Pattern PATTERN = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
        private Object o;
        private String validatorParam;

        public VadatorParam(Object o, String validatorParam) {
            this.o = o;
            this.validatorParam = validatorParam;
        }

        public boolean invoke() {
            Pattern pattern = Pattern.compile(validatorParam);
            Matcher m = pattern.matcher(o.toString());
            return m.matches();
        }
        public static String getLengthAndRange(String type,Object o,boolean fa){
            int subLegtn = type.indexOf("[") ;
            String valiMsg= type.substring(0, subLegtn);
            String methodName = type.toLowerCase();
            Matcher matcher = PATTERN.matcher(methodName);
            String matcherMethod="";
            while (matcher.find()){
                matcherMethod=matcher.group().trim();
            }
            boolean flage;
            String tagerMsg = matcherMethod;
            Map<String, Object> env = Maps.newHashMap();
            if (fa){
                env.put("x",o.toString().length());
            }else {
                env.put("x",Integer.parseInt(o.toString()));
            }
            String[] sub =matcherMethod.split("x");
            if(sub.length>1){
                flage = (Boolean) AviatorEvaluator.compile(sub[0]+"x").execute(env) && (Boolean) AviatorEvaluator.compile("x"+sub[1]).execute(env);
                return flage==true?null: MessageFormat.format(ValidatorMsgEnums.getDesc(valiMsg),tagerMsg);
            }
            flage = (Boolean) AviatorEvaluator.compile(matcherMethod).execute(env);
            return flage==true?null: MessageFormat.format(ValidatorMsgEnums.getDesc(valiMsg),tagerMsg);
        }
    }